Skip to main content
Version: I2024.1.3

Example Code for a Webhook Receiver Server

The following example applications -- one in Go, the other in Java -- are generic, universal webhook receivers that accept the POST from the AtScale platform and simply echo some of the posted parameters.

Example in Go

package main  
import (
  "fmt"
  "log"
  "net/http"
  "strings"
)

func test(w http.ResponseWriter, r \*http.Request) {
  r.ParseForm() // parse arguments, you have to call this by yourself
  fmt.Println(r.Form) // print form information in server side
  fmt.Println("path", r.URL.Path)
  fmt.Println("scheme", r.URL.Scheme)
  fmt.Println(r.Form\["url_long"\])
  for k, v := range r.Form {
    fmt.Println("key:", k)
    fmt.Println("val:", strings.Join(v, ""))
  }
  fmt.Fprintf(w, "Hello World!") // send data to client side
}

func main() {
  http.HandleFunc("/webhook", test) // set router
  err := http.ListenAndServe(":3030", nil) // set listen port
  if err != nil {
    log.Fatal("ListenAndServe: ", err)
  }
}

Example in Java

import java.io.IOException;  
import java.io.OutputStream;
import java.net.InetSocketAddress;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
/\*
\* a simple static http server
\*/
public class Webhook {
  public static void main(String\[\] args) throws Exception {
    HttpServer server = HttpServer.create(new InetSocketAddress(3030),
0);
    server.createContext("/test", new MyHandler());
    server.setExecutor(null); // creates a default executor
    System.out.println("starting"); server.start();
  }

  static class MyHandler implements HttpHandler {
    public void handle(HttpExchange exchange) throws IOException {
      String response = "finished";
      exchange.sendResponseHeaders(200, response.length());
      OutputStream os = exchange.getResponseBody();
      os.write(response.getBytes());
      os.close();
      System.out.println("uri is " + exchange.getRequestURI());
    }
  }
}

Related reference

Engine Webhooks