forked from tildetown/bbj2
		
	serve HTTP
This commit is contained in:
		
							parent
							
								
									a87c941bb3
								
							
						
					
					
						commit
						9b3ef7dc34
					
				| @ -4,6 +4,7 @@ import ( | |||||||
| 	"flag" | 	"flag" | ||||||
| 	"fmt" | 	"fmt" | ||||||
| 	"io" | 	"io" | ||||||
|  | 	"net/http" | ||||||
| 	"os" | 	"os" | ||||||
| ) | ) | ||||||
| 
 | 
 | ||||||
| @ -15,16 +16,26 @@ type iostreams struct { | |||||||
| type Opts struct { | type Opts struct { | ||||||
| 	ConfigPath string | 	ConfigPath string | ||||||
| 	IO         iostreams | 	IO         iostreams | ||||||
|  | 	Log        func(string) | ||||||
|  | 	Logf       func(string, ...interface{}) | ||||||
| } | } | ||||||
| 
 | 
 | ||||||
| func main() { | func main() { | ||||||
| 	var configFlag = flag.String("config", "config.yml", "A path to a config file.") | 	var configFlag = flag.String("config", "config.yml", "A path to a config file.") | ||||||
| 	flag.Parse() | 	flag.Parse() | ||||||
| 	opts := Opts{ | 	io := iostreams{ | ||||||
| 		ConfigPath: *configFlag, |  | ||||||
| 		IO: iostreams{ |  | ||||||
| 		Err: os.Stderr, | 		Err: os.Stderr, | ||||||
| 		Out: os.Stdout, | 		Out: os.Stdout, | ||||||
|  | 	} | ||||||
|  | 	opts := Opts{ | ||||||
|  | 		ConfigPath: *configFlag, | ||||||
|  | 		IO:         io, | ||||||
|  | 		// TODO use real logger | ||||||
|  | 		Log: func(s string) { | ||||||
|  | 			fmt.Fprintln(io.Out, s) | ||||||
|  | 		}, | ||||||
|  | 		Logf: func(s string, args ...interface{}) { | ||||||
|  | 			fmt.Fprintf(io.Out, s, args...) | ||||||
| 		}, | 		}, | ||||||
| 	} | 	} | ||||||
| 
 | 
 | ||||||
| @ -41,7 +52,27 @@ func _main(opts Opts) error { | |||||||
| 		os.Exit(1) | 		os.Exit(1) | ||||||
| 	} | 	} | ||||||
| 
 | 
 | ||||||
| 	fmt.Printf("DBG %#v\n", cfg.InstanceName) | 	setupAPI(opts, *cfg) | ||||||
|  | 
 | ||||||
|  | 	// TODO TLS or SSL or something | ||||||
|  | 	opts.Logf("starting server at %s:%d\n", cfg.Host, cfg.Port) | ||||||
|  | 	if err := http.ListenAndServe(fmt.Sprintf("%s:%d", cfg.Host, cfg.Port), nil); err != nil { | ||||||
|  | 		return fmt.Errorf("http server exited with error: %w", err) | ||||||
|  | 	} | ||||||
| 
 | 
 | ||||||
| 	return nil | 	return nil | ||||||
| } | } | ||||||
|  | 
 | ||||||
|  | func handler(opts Opts, cfg Config, f http.HandlerFunc) http.HandlerFunc { | ||||||
|  | 	// TODO make this more real | ||||||
|  | 	return func(w http.ResponseWriter, req *http.Request) { | ||||||
|  | 		opts.Log(req.URL.Path) | ||||||
|  | 		f(w, req) | ||||||
|  | 	} | ||||||
|  | } | ||||||
|  | 
 | ||||||
|  | func setupAPI(opts Opts, cfg Config) { | ||||||
|  | 	http.HandleFunc("/instance", handler(opts, cfg, func(w http.ResponseWriter, req *http.Request) { | ||||||
|  | 		io.WriteString(w, cfg.InstanceName) | ||||||
|  | 	})) | ||||||
|  | } | ||||||
|  | |||||||
		Loading…
	
	
			
			x
			
			
		
	
		Reference in New Issue
	
	Block a user