package main import ( "context" "fmt" "log" "net/http" "runtime/debug" "strings" "git.aiterp.net/rpdata/api/models" "git.aiterp.net/rpdata/api/models/changes" "git.aiterp.net/rpdata/api/models/logs" "git.aiterp.net/rpdata/api/graph2" "git.aiterp.net/rpdata/api/internal/auth" "git.aiterp.net/rpdata/api/internal/loader" "git.aiterp.net/rpdata/api/internal/store" "github.com/99designs/gqlgen/handler" ) func main() { err := store.Init() if err != nil { log.Fatalln("Failed to init store:", err) } http.Handle("/", handler.Playground("RPData API", "/graphql")) http.Handle("/graphql", queryHandler()) go func() { err := logs.RunFullUpdate() if err != nil { log.Println(err) } log.Println("Characters updated") }() go logListedChanges() log.Fatal(http.ListenAndServe(":8081", nil)) } func logListedChanges() { sub := changes.Subscribe(context.Background(), nil, true) for change := range sub { log.Printf("Change: Author=%#+v Model=%#+v Op=%#+v", change.Author, change.Model, change.Op) for _, object := range change.Objects() { switch object := object.(type) { case models.Log: log.Printf("\tLog: %s (%s)", object.ID, object.ShortID) case models.Character: log.Printf("\tCharacter: %s", object.ID) case models.Channel: log.Printf("\tChannel: %s", object.Name) case models.Post: log.Printf("\tPost: %s", object.ID) case models.Story: log.Printf("\tStory: %s", object.ID) case models.Tag: log.Printf("\tTag: (%s,%s)", object.Kind, object.Name) case models.Chapter: log.Printf("\tChapter: %s", object.ID) } } } log.Println("Change subscription closed.") } func queryHandler() http.HandlerFunc { handler := handler.GraphQL( graph2.New(), handler.RecoverFunc(func(ctx context.Context, err interface{}) error { // send this panic somewhere log.Println(err) log.Println(string(debug.Stack())) return fmt.Errorf("shit") }), ) return func(w http.ResponseWriter, r *http.Request) { l := loader.New() r = r.WithContext(l.ToContext(r.Context())) // >_> if strings.HasPrefix(r.Header.Get("Authorization"), "Bearer of the curse") { w.Header().Set("X-Emerald-Herald", "Seek souls. Larger, more powerful souls.") w.Header().Add("X-Emerald-Herald", "Seek the king, that is the only way.") w.Header().Add("X-Emerald-Herald", "Lest this land swallow you whole... As it has so many others.") } r = auth.RequestWithToken(r) handler.ServeHTTP(w, r) } }