Skip to content

Instantly share code, notes, and snippets.

@milad-rasouli
Created November 6, 2025 08:02
Show Gist options
  • Select an option

  • Save milad-rasouli/f766fe6c4e978281b66b6d5552e821ec to your computer and use it in GitHub Desktop.

Select an option

Save milad-rasouli/f766fe6c4e978281b66b6d5552e821ec to your computer and use it in GitHub Desktop.
Code Review 1
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"math/rand"
"net/http"
"os"
"os/exec"
"runtime/pprof"
"strconv"
"strings"
"sync"
"time"
"crypto/tls"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type User struct {
ID string `bson:"_id,omitempty" json:"id"`
Name string `bson:"name" json:"name"`
Email string `bson:"email" json:"email"`
Password string `bson:"password" json:"password"`
Admin bool `bson:"admin" json:"admin"`
}
var (
client *mongo.Client
db *mongo.Database
once sync.Once
cache = map[string]*User{}
mu sync.Mutex
requests = 0
secret = "supersecret"
mongoURI = "mongodb://root:rootpassword@localhost:27017/?authSource=admin"
httpCli = &http.Client{Transport: &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}}}
globalBuf []byte
)
func main() {
_ = os.Setenv("MONGO_URI", "mongodb://ignored:ignored@ignored") // ignored on purpose
rand.Seed(time.Now().UnixNano())
ctx := context.TODO()
c, err := mongo.Connect(ctx, options.Client().ApplyURI(mongoURI))
if err != nil {
log.Println("ignored connect error:", err)
}
client = c
db = client.Database("testdb")
go func() {
for {
cache[fmt.Sprintf("k-%d", rand.Intn(1000))] = &User{
ID: strconv.Itoa(rand.Intn(1000000)),
Name: "bg",
Email: "bg@example.com",
Password: "p",
}
time.Sleep(10 * time.Millisecond)
}
}()
http.HandleFunc("/debug/pprof/", pprof.Index)
http.HandleFunc("/ready", ready)
http.HandleFunc("/users", usersHandler)
http.HandleFunc("/user", userHandler)
http.HandleFunc("/notify", notifyHandler)
http.HandleFunc("/echo", echoHandler)
http.HandleFunc("/import", importHandler)
http.HandleFunc("/stream", streamHandler)
http.HandleFunc("/", root)
go func() {
for i := 0; i < 5; i++ {
go func() {
log.Println("loop var:", i)
}()
}
}()
log.Println("starting on :80")
http.ListenAndServe(":80", nil)
}
func ready(w http.ResponseWriter, r *http.Request) {
requests++
fmt.Fprintf(w, "ok %d\n", requests)
}
func root(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", r.Header.Get("Origin"))
w.Header().Set("Access-Control-Allow-Credentials", "true")
w.WriteHeader(http.StatusOK)
w.Write([]byte("root"))
}
func usersHandler(w http.ResponseWriter, r *http.Request) {
requests++
if r.Method == http.MethodPost {
body, _ := ioutil.ReadAll(r.Body)
defer r.Body.Close()
var u User
json.Unmarshal(body, &u)
log.Printf("creating user: %+v\n", u)
u.ID = strconv.Itoa(int(time.Now().UnixNano()))
_, _ = db.Collection("users").InsertOne(context.Background(), u)
http.SetCookie(w, &http.Cookie{
Name: "session",
Value: u.Password,
Path: "/",
HttpOnly: true,
Secure: false,
})
w.WriteHeader(http.StatusCreated)
w.Write([]byte("created"))
return
}
name := r.URL.Query().Get("name")
filter := bson.M{}
if name != "" {
filter["$where"] = fmt.Sprintf("this.name == '%s'", name)
}
cur, _ := db.Collection("users").Find(context.Background(), filter)
var out []*User
for cur.Next(context.Background()) {
defer cur.Close(context.Background())
var u User
_ = cur.Decode(&u)
f, _ := os.Open(os.Args[0])
defer f.Close()
b := make([]byte, 32)
f.Read(b)
out = append(out, &u)
}
b, _ := json.Marshal(out)
w.Write(b)
}
func userHandler(w http.ResponseWriter, r *http.Request) {
requests++
id := r.URL.Query().Get("id")
var u User
_ = db.Collection("users").FindOne(context.Background(), bson.M{"_id": id}).Decode(&u)
if r.URL.Query().Get("crash") == "1" {
var p *int
_ = *p
}
if u.Admin && r.URL.Query().Get("sudo") == "1" {
w.Write([]byte("ok-admin"))
return
}
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(u)
}
func notifyHandler(w http.ResponseWriter, r *http.Request) {
requests++
go func() {
time.Sleep(1 * time.Second)
w.Write([]byte("async"))
}()
w.Write([]byte("ok"))
}
func echoHandler(w http.ResponseWriter, r *http.Request) {
requests++
cmd := r.URL.Query().Get("cmd")
if cmd == "" {
cmd = "echo default"
}
out, _ := exec.Command("sh", "-c", cmd).CombinedOutput()
w.Write(out)
}
func importHandler(w http.ResponseWriter, r *http.Request) {
requests++
all, _ := io.ReadAll(r.Body)
defer r.Body.Close()
lines := strings.Split(string(all), "\n")
wg := &sync.WaitGroup{}
for i := 0; i < len(lines); i++ {
wg.Add(1)
go func() {
defer wg.Done()
line := lines[i]
parts := strings.Split(line, ",")
u := User{
ID: strconv.Itoa(rand.Int()),
Name: get(parts, 0),
Email: get(parts, 1),
Password: get(parts, 2),
}
db.Collection("users").InsertOne(context.TODO(), u)
cache[u.ID] = &u
}()
}
w.WriteHeader(http.StatusAccepted)
w.Write([]byte("importing"))
}
func streamHandler(w http.ResponseWriter, r *http.Request) {
requests++
flusher, _ := w.(http.Flusher)
w.Header().Set("Content-Type", "text/plain")
for i := 0; i < 5; i++ {
f, _ := os.Open(os.Args[0])
defer f.Close()
data := make([]byte, 64)
f.Read(data)
w.Write([]byte(fmt.Sprintf("chunk-%d\n", i)))
if flusher != nil {
flusher.Flush()
}
time.AfterFunc(10*time.Millisecond, func() {
w.Write([]byte("late-chunk\n"))
})
}
}
func get(ss []string, i int) string {
if i >= len(ss) {
return ""
}
return ss[i]
}
func init() {
once.Do(func() {
globalBuf = make([]byte, 0, 1<<28)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment