-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathmain.go
More file actions
132 lines (114 loc) · 3.8 KB
/
main.go
File metadata and controls
132 lines (114 loc) · 3.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
package main
import (
"context"
"fmt"
"github.com/SebastienMelki/sebuf/examples/simple-api/api/proto/models"
"github.com/SebastienMelki/sebuf/examples/simple-api/api/proto/services"
"log"
"net/http"
"time"
)
// Note: Uncomment and use after running 'buf generate'
type UserService struct {
users map[string]*models.User
nextID int
}
func NewUserService() *UserService {
return &UserService{
users: make(map[string]*models.User),
nextID: 1,
}
}
func (s *UserService) CreateUser(ctx context.Context, req *models.CreateUserRequest) (*models.User, error) {
user := &models.User{
Id: fmt.Sprintf("user-%d", s.nextID),
Name: req.Name,
Email: req.Email,
CreatedAt: time.Now().Unix(),
}
s.nextID++
s.users[user.Id] = user
return user, nil
}
func (s *UserService) GetUser(ctx context.Context, req *models.GetUserRequest) (*models.User, error) {
user, exists := s.users[req.Id]
if !exists {
return nil, fmt.Errorf("user not found: %s", req.Id)
}
return user, nil
}
func (s *UserService) Login(ctx context.Context, req *models.LoginRequest) (*models.LoginResponse, error) {
var userEmail string
// Handle different authentication methods using the oneof field
switch auth := req.AuthMethod.(type) {
case *models.LoginRequest_Email:
// Email authentication
userEmail = auth.Email.Email
// In production, verify password hash
log.Printf("Email login: %s", auth.Email.Email)
case *models.LoginRequest_Token:
// Token authentication
log.Printf("Token login: %s", auth.Token.Token)
userEmail = "user@fromtoken.com" // In production, decode token
case *models.LoginRequest_Social:
// Social authentication
log.Printf("Social login via %s", auth.Social.Provider)
userEmail = "user@social.com" // In production, validate with provider
default:
return nil, fmt.Errorf("unknown authentication method")
}
// Find or create user
var user *models.User
for _, u := range s.users {
if u.Email == userEmail {
user = u
break
}
}
if user == nil {
// Create new user for demo
user = &models.User{
Id: fmt.Sprintf("user-%d", s.nextID),
Name: "Demo User",
Email: userEmail,
CreatedAt: time.Now().Unix(),
}
s.nextID++
s.users[user.Id] = user
}
return &models.LoginResponse{
AccessToken: fmt.Sprintf("token_%s_%d", user.Id, time.Now().Unix()),
RefreshToken: fmt.Sprintf("refresh_%s_%d", user.Id, time.Now().Unix()),
ExpiresIn: 3600,
User: user,
}, nil
}
func main() {
service := services.NewMockUserServiceServer()
mux := http.NewServeMux()
// Register the HTTP handlers (generated by protoc-gen-go-http)
if err := services.RegisterUserServiceServer(service, services.WithMux(mux)); err != nil {
log.Fatal(err)
}
fmt.Println("Server starting on :8080")
fmt.Println("Endpoints:")
fmt.Println(" POST /api/v1/users - Create user")
fmt.Println(" POST /api/v1/users/get - Get user")
fmt.Println(" POST /api/v1/auth/login - Login")
fmt.Println("")
fmt.Println("Example requests:")
fmt.Println("")
fmt.Println("Create user:")
fmt.Println(" curl -X POST http://localhost:8080/api/v1/users \\")
fmt.Println(" -H 'Content-Type: application/json' \\")
fmt.Println(" -d '{\"name\": \"John Doe\", \"email\": \"john@example.com\"}'")
fmt.Println("")
fmt.Println("Login with email:")
fmt.Println(" curl -X POST http://localhost:8080/api/v1/auth/login \\")
fmt.Println(" -H 'Content-Type: application/json' \\")
fmt.Println(" -d '{\"email\": {\"email\": \"john@example.com\", \"password\": \"secret\"}}'")
fmt.Println("")
fmt.Println("In Go code, you can construct the request manually:")
fmt.Println(" loginReq := &models.LoginRequest{AuthMethod: &models.LoginRequest_Email{Email: &models.LoginRequest_EmailAuth{Email: \"john@example.com\", Password: \"secret\"}}}")
log.Fatal(http.ListenAndServe(":8080", mux))
}