/* Copyright © 2019 Darko Luketic Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "fmt" "net" "net/http" "os" "strings" "time" "github.com/dalu/chromedom/server" "github.com/spf13/cobra" ) var ( binary string duration time.Duration maxmem int addr string ) // serveCmd represents the serve command var serveCmd = &cobra.Command{ Use: "serve", Short: "", Long: ``, RunE: func(cmd *cobra.Command, args []string) error { s := http.DefaultServeMux h := server.NewHandler(binary, duration, maxmem) s.Handle("/", h) if strings.HasPrefix(addr, "unix:") { return runUnix(strings.TrimPrefix(addr, "unix:"), s) } else { fmt.Printf("Listening and serving HTTP on %s", addr) return http.ListenAndServe(addr, s) } }, } func runUnix(file string, engine *http.ServeMux) (err error) { fmt.Printf("Listening and serving HTTP on unix:/%s", file) os.Remove(file) listener, err := net.Listen("unix", file) if err != nil { return } defer listener.Close() if err := os.Chmod(file, 0777); err != nil { return err } err = http.Serve(listener, engine) return } func init() { rootCmd.AddCommand(serveCmd) serveCmd.Flags().StringVarP(&binary, "binary", "b", "/usr/bin/google-chrome", "chrome, chromium or headless binary path") serveCmd.Flags().DurationVarP(&duration, "duration", "d", 60*time.Minute, "how long the values live in the cache") serveCmd.Flags().IntVarP(&maxmem, "maxmem", "m", 512, "maximum memory in MB the cache may use") serveCmd.Flags().StringVarP(&addr, "addr", "a", "localhost:9292", "ip:port pair to listen on, or prefixed with unix: the unix socket path to listen on") }