|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "fmt" |
| 6 | + "go.etcd.io/gofail/integration/server/failpoints" |
| 7 | + "log" |
| 8 | + "net/http" |
| 9 | + "os" |
| 10 | + "reflect" |
| 11 | + "strings" |
| 12 | +) |
| 13 | + |
| 14 | +var funcMap = map[string]interface{}{ |
| 15 | + "ExampleFunc": failpoints.ExampleFunc, |
| 16 | + "ExampleOneLineFunc": failpoints.ExampleOneLineFunc, |
| 17 | + "ExampleLabelsFunc": failpoints.ExampleLabelsFunc, |
| 18 | +} |
| 19 | + |
| 20 | +func callFuncByName(name string, args []string) (interface{}, error) { |
| 21 | + fn, exists := funcMap[name] |
| 22 | + if !exists { |
| 23 | + return nil, fmt.Errorf("function %s does not exist", name) |
| 24 | + } |
| 25 | + |
| 26 | + fnValue := reflect.ValueOf(fn) |
| 27 | + expectedNArgs := fnValue.Type().NumIn() |
| 28 | + gotNArgs := len(args) |
| 29 | + if expectedNArgs != gotNArgs { |
| 30 | + return nil, fmt.Errorf("wrong number of arguments for function %s. "+ |
| 31 | + "Expected %d, got %d", name, expectedNArgs, gotNArgs) |
| 32 | + } |
| 33 | + |
| 34 | + in := make([]reflect.Value, len(args)) |
| 35 | + for i, arg := range args { |
| 36 | + in[i] = reflect.ValueOf(arg) |
| 37 | + } |
| 38 | + |
| 39 | + result := fnValue.Call(in) |
| 40 | + if len(result) == 0 { |
| 41 | + return nil, nil |
| 42 | + } |
| 43 | + return result[0].Interface(), nil |
| 44 | +} |
| 45 | + |
| 46 | +func handler(w http.ResponseWriter, r *http.Request) { |
| 47 | + log.Printf("received request: %v", r) |
| 48 | + pathParts := strings.Split(r.URL.Path, "/") |
| 49 | + if len(pathParts) < 3 { |
| 50 | + http.Error(w, "invalid URL path", http.StatusBadRequest) |
| 51 | + return |
| 52 | + } |
| 53 | + funcName := pathParts[2] |
| 54 | + args := r.URL.Query()["args"] |
| 55 | + |
| 56 | + result, err := callFuncByName(funcName, args) |
| 57 | + if err != nil { |
| 58 | + http.Error(w, err.Error(), http.StatusBadRequest) |
| 59 | + return |
| 60 | + } |
| 61 | + |
| 62 | + response, err := json.Marshal(result) |
| 63 | + if err != nil { |
| 64 | + http.Error(w, "failed to marshal response", http.StatusInternalServerError) |
| 65 | + return |
| 66 | + } |
| 67 | + |
| 68 | + w.Header().Set("Content-Type", "application/json") |
| 69 | + _, err = w.Write(response) |
| 70 | + if err != nil { |
| 71 | + http.Error(w, "failed to write response", http.StatusInternalServerError) |
| 72 | + } |
| 73 | +} |
| 74 | + |
| 75 | +func main() { |
| 76 | + if len(os.Args) < 2 { |
| 77 | + log.Fatal("Port number is required as a command line argument") |
| 78 | + } |
| 79 | + port := os.Args[1] |
| 80 | + |
| 81 | + http.HandleFunc("/call/", handler) |
| 82 | + log.Printf("Starting server on :%s", port) |
| 83 | + log.Fatal(http.ListenAndServe(":"+port, nil)) |
| 84 | +} |
0 commit comments