3csv.go 746 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. package main
  2. import (
  3. "database/sql"
  4. "fmt"
  5. "net/http"
  6. "encoding/csv"
  7. _ "github.com/go-sql-driver/mysql"
  8. "strconv"
  9. )
  10. // Tags are not actually used at this point. Probably never.
  11. type User struct {
  12. Name string `csv:"name"`
  13. Email string `csv:"email"`
  14. ID int `csv:"int"`
  15. }
  16. func userRouter(w http.ResponseWriter, r *http.Request) {
  17. ourUser := User{
  18. Name: "Bill Smith",
  19. Email: "bill,smith@example.com",
  20. ID: 100,
  21. }
  22. row := []string{
  23. ourUser.Name,
  24. ourUser.Email,
  25. strconv.Itoa(ourUser.ID),
  26. }
  27. csvWriter := csv.NewWriter(w)
  28. csvWriter.Write(row)
  29. csvWriter.Flush()
  30. }
  31. var database *sql.DB
  32. func main() {
  33. fmt.Println("Starting CSV server")
  34. http.HandleFunc("/user", userRouter)
  35. http.ListenAndServe(":8080", nil)
  36. }