2017-08-20 03:52:42 +05:30
|
|
|
package http
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"net"
|
|
|
|
"net/http"
|
|
|
|
"os"
|
|
|
|
"os/signal"
|
|
|
|
"strings"
|
|
|
|
"syscall"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/gorilla/mux"
|
|
|
|
"github.com/mono83/slf/wd"
|
|
|
|
|
2018-02-16 02:43:57 +05:30
|
|
|
"github.com/elyby/chrly/interfaces"
|
2017-08-20 03:52:42 +05:30
|
|
|
)
|
|
|
|
|
|
|
|
type Config struct {
|
|
|
|
ListenSpec string
|
|
|
|
|
|
|
|
SkinsRepo interfaces.SkinsRepository
|
|
|
|
CapesRepo interfaces.CapesRepository
|
|
|
|
Logger wd.Watchdog
|
2018-01-23 21:13:37 +05:30
|
|
|
Auth interfaces.AuthChecker
|
2017-08-20 03:52:42 +05:30
|
|
|
}
|
|
|
|
|
|
|
|
func (cfg *Config) Run() error {
|
|
|
|
cfg.Logger.Info(fmt.Sprintf("Starting, HTTP on: %s\n", cfg.ListenSpec))
|
|
|
|
|
|
|
|
listener, err := net.Listen("tcp", cfg.ListenSpec)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
server := &http.Server{
|
|
|
|
ReadTimeout: 60 * time.Second,
|
|
|
|
WriteTimeout: 60 * time.Second,
|
|
|
|
MaxHeaderBytes: 1 << 16,
|
|
|
|
Handler: cfg.CreateHandler(),
|
|
|
|
}
|
|
|
|
|
|
|
|
go server.Serve(listener)
|
|
|
|
|
|
|
|
s := waitForSignal()
|
|
|
|
cfg.Logger.Info(fmt.Sprintf("Got signal: %v, exiting.", s))
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (cfg *Config) CreateHandler() http.Handler {
|
|
|
|
router := mux.NewRouter().StrictSlash(true)
|
|
|
|
|
|
|
|
router.HandleFunc("/skins/{username}", cfg.Skin).Methods("GET")
|
|
|
|
router.HandleFunc("/cloaks/{username}", cfg.Cape).Methods("GET").Name("cloaks")
|
|
|
|
router.HandleFunc("/textures/{username}", cfg.Textures).Methods("GET")
|
|
|
|
router.HandleFunc("/textures/signed/{username}", cfg.SignedTextures).Methods("GET")
|
|
|
|
// Legacy
|
|
|
|
router.HandleFunc("/skins", cfg.SkinGET).Methods("GET")
|
|
|
|
router.HandleFunc("/cloaks", cfg.CapeGET).Methods("GET")
|
2018-01-23 21:13:37 +05:30
|
|
|
// API
|
|
|
|
router.Handle("/api/skins", cfg.Authenticate(http.HandlerFunc(cfg.PostSkin))).Methods("POST")
|
2018-01-24 01:28:42 +05:30
|
|
|
router.Handle("/api/skins/id:{id:[0-9]+}", cfg.Authenticate(http.HandlerFunc(cfg.DeleteSkinByUserId))).Methods("DELETE")
|
|
|
|
router.Handle("/api/skins/{username}", cfg.Authenticate(http.HandlerFunc(cfg.DeleteSkinByUsername))).Methods("DELETE")
|
2017-08-20 03:52:42 +05:30
|
|
|
// 404
|
|
|
|
router.NotFoundHandler = http.HandlerFunc(cfg.NotFound)
|
|
|
|
|
|
|
|
return router
|
|
|
|
}
|
|
|
|
|
|
|
|
func parseUsername(username string) string {
|
|
|
|
const suffix = ".png"
|
|
|
|
if strings.HasSuffix(username, suffix) {
|
|
|
|
username = strings.TrimSuffix(username, suffix)
|
|
|
|
}
|
|
|
|
|
|
|
|
return username
|
|
|
|
}
|
|
|
|
|
|
|
|
func waitForSignal() os.Signal {
|
|
|
|
ch := make(chan os.Signal)
|
|
|
|
signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
|
|
|
|
|
|
|
|
return <-ch
|
|
|
|
}
|