a simple url shortener in Go (check it out at qurl.org)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

88 lines
1.4 KiB

  1. package main
  2. import (
  3. "flag"
  4. "fmt"
  5. "io"
  6. "log"
  7. "os"
  8. "time"
  9. )
  10. func main() {
  11. pkg := flag.String("p", "", "package")
  12. name := flag.String("n", "", "const name")
  13. inputfn := flag.String("i", "", "input file")
  14. outputfn := flag.String("o", "", "output file")
  15. flag.Parse()
  16. if *pkg == "" {
  17. log.Fatal("pkg required")
  18. }
  19. if *name == "" {
  20. log.Fatal("name required")
  21. }
  22. if *inputfn == "" {
  23. log.Fatal("input file required")
  24. }
  25. if *outputfn == "" {
  26. *outputfn = *inputfn + ".go"
  27. }
  28. omod := fmod(*outputfn)
  29. imod := fmod(*inputfn)
  30. if omod.After(imod) {
  31. log.Printf("Refusing to update %s\n", *outputfn)
  32. return
  33. }
  34. ifile, err := os.Open(*inputfn)
  35. if err != nil {
  36. log.Fatal(err)
  37. }
  38. defer ifile.Close()
  39. ofile, err := os.OpenFile(*outputfn, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0660)
  40. if err != nil {
  41. log.Fatal(err)
  42. }
  43. defer ofile.Close()
  44. fmt.Fprintf(ofile, "package %s\n\nvar %s = []byte{", *pkg, *name)
  45. buf := make([]byte, 4096)
  46. for c := 0; ; {
  47. i, err := ifile.Read(buf)
  48. if err != nil {
  49. if err != io.EOF {
  50. log.Fatal(err)
  51. }
  52. break
  53. }
  54. for j := 0; j < i; j++ {
  55. if (c % 13) == 0 {
  56. fmt.Fprintf(ofile, "\n\t")
  57. } else {
  58. fmt.Fprintf(ofile, " ")
  59. }
  60. fmt.Fprintf(ofile, "0x%02x,", buf[j])
  61. c++
  62. }
  63. }
  64. fmt.Fprintf(ofile, "\n}\n")
  65. }
  66. func fmod(fn string) time.Time {
  67. fi, err := os.Stat(fn)
  68. if err != nil {
  69. if os.IsNotExist(err) {
  70. return time.Time{}
  71. }
  72. log.Fatal(err)
  73. }
  74. return fi.ModTime()
  75. }